<?php

Class User extends CI_Model {

    function get($id) {

        $this->db->select('*');
        $this->db->from('users');

        $this->db->where('id', $id);

        $query = $this->db->get();

        return $query->row_array();
    }

    function getLoggedUser() {
//        $CI = & get_instance();
//        $CI->load->database();
//        $CI->load->session();

        if (!$this->session->userdata('logged_in')) {
            return false;
        }  else {
            $loggedUser = $this->session->userdata('logged_in');


        $this->db->select('id, username, password, gid, su, title, code');
        $this->db->from('users');
        $this->db->where('CONCAT(MD5(id), MD5(username)) =', $loggedUser['sscode']);
        $this->db->limit(1);
        $query = $this->db->get();

        $rows = $query->result();
        $loggedUser = $rows[0];
        return $loggedUser;
        }

        
    }

    function login($username, $password) {
        $this->db->select('id, username, password, gid, su, title');
        $this->db->from('users');
        $this->db->where('username', $username);
        $this->db->where('password', MD5($password));
        $this->db->limit(1);

        $query = $this->db->get();

        if ($query->num_rows() == 1) {
            return $query->result();
        } else {
            return false;
        }
    }

    function get_unique_locations() {

        $this->db->select('location');
        $this->db->distinct();
        $this->db->from('users');

        //$this->db->where('id', $id);

        $query = $this->db->get();

        return $query->result_array();
    }

    function user_by_group() {
        $institute_id = $this->session->userdata('institute_id');
        $user_group = array();
        $user_group[] = array('Group Name', 'Registered users');
        $query = $this->db->query("select * from user_group where institute_id = '$institude_id'");
        $result = $query->result_array();
        foreach ($result as $value) {
            $gid = $value['gid'];
            $group_name = $value['group_name'];
            $query = $this->db->query("select * from users where gid='$gid' and institute_id = '$institute_id' ");
            $nou = $query->num_rows();
            $user_group[] = array($group_name, intval($nou));
        }
        return $user_group;
    }

    function user_list($limit) {
        $institute_id = $this->session->userdata('institute_id');
        $this->db->select('*');
        $this->db->from('users');
        //$this->db->where("institute_id", $institute_id);
        if ($this->input->post('search_type')) {
            $search_type = $this->input->post('search_type');
            $search = $this->input->post('search');
            $this->db->like($search_type, $search);
        }
        //$this->db->limit($this->config->item('number_of_rows'), $limit);
        $this->db->order_by("id", "desc");
        $query = $this->db->get();

        if ($query->num_rows() >= 1) {
            return $query->result();
        } else {
            return false;
        }
    }

    function get_list($wheres = array()) {
        //$institute_id = $this->session->userdata('institute_id');
        $this->db->select('*');
        $this->db->from('users');
        //$this->db->where("institute_id", $institute_id);
//        if ($this->input->post('search_type')) {
//            $search_type = $this->input->post('search_type');
//            $search = $this->input->post('search');
//            $this->db->like($search_type, $search);
//        }

        foreach ($wheres as $key => $value) {
            $this->db->where($key, $value);
        }

        //$this->db->limit($this->config->item('number_of_rows'), '0');
        $this->db->order_by("id", "desc");
        $query = $this->db->get();

        if ($query->num_rows() >= 1) {
            return $query->result_array();
        } else {
            return false;
        }
    }

    function retrieve($fields, $wheres) {
        //$institute_id = $this->session->userdata('institute_id');
        $this->db->select($fields);
        $this->db->from('users');
        //$this->db->where("institute_id", $institute_id);
//        if ($this->input->post('search_type')) {
//            $search_type = $this->input->post('search_type');
//            $search = $this->input->post('search');
//            $this->db->like($search_type, $search);
//        }

        
        
        if ($wheres != false) {
            foreach ($wheres as $key => $value) {
                $this->db->where($key, $value);
            }
        }
        //$this->db->limit($this->config->item('number_of_rows'), '0');
        $this->db->order_by("id", "desc");
        $query = $this->db->get();

        if ($query->num_rows() >= 1) {
            return $query->result_array();
        } else {
            return false;
        }
    }

    function get_list_by_title($allowTitles, $wheres = array()) {

        $this->db->select('*');
        $this->db->from('users');

        $this->db->where_in('title', $allowTitles);

        foreach ($wheres as $key => $value) {
            $this->db->where($key, $value);
        }
        //$this->db->limit($recordsPerPage, $startFrom);
        //$this->db->limit($this->config->item('number_of_rows'), '0');
        //$this->db->order_by("id", "asc");
        $query = $this->db->get();

        if ($query->num_rows() >= 1) {
            $users = $query->result_array();
            foreach ($users as &$aUser) {
                $this->db->select('name')->from('users')->where('code', $aUser['teamleader_code']);
                $q1 = $this->db->get();
                $tl = $q1->row_array();
                $aUser['teamleader_name'] = $tl['name'];
                
                $this->db->select('name')->from('users')->where('code', $aUser['supervisor_code']);
                $q1 = $this->db->get();
                $tl = $q1->row_array();
                $aUser['supervisor_name'] = $tl['name'];
                
                $this->db->select('name')->from('users')->where('code', $aUser['rsm_code']);
                $q1 = $this->db->get();
                $tl = $q1->row_array();
                $aUser['rsm_name'] = $tl['name'];
            }
            
            //return $query->result_array();
            return $users;
        } else {
            return false;
        }
    }

    function get_list_by_title_and_group($allowTitles, $gids) {

        $this->db->select('*');
        $this->db->from('users');

        $this->db->where_in('title', $allowTitles);

        $this->db->where_in('gid', $gids);

        //$this->db->limit($this->config->item('number_of_rows'), '0');
        //$this->db->order_by("id", "asc");
        $query = $this->db->get();

        if ($query->num_rows() >= 1) {
            return $query->result_array();
        } else {
            return false;
        }
    }

    function remove_user($id) {
        $institute_id = $this->session->userdata('institute_id');

        $query = $this->db->query("select * from users where id='$id' and institute_id = '$institute_id' ");
        $result = $query->row_array();
        if ($result['main_su_admin'] != "1") {
            if ($this->db->delete('users', array('id' => $id, 'institute_id' => $institute_id))) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    // Tam
    function insert($newUser) {
        if ($this->db->insert('users', $newUser)) {
            return "Đã thêm xong!";
        } else {
            return "Unable to add user";
        }
    }
    
    // Tam
    function import($rows) {
        
        $fails = array();
        for($i = 1; $i<count($rows); $i++)
        {
            $row = $rows[$i];
            if ($row['1'] != '' ) {
                    
                $gid = 0;
                switch ($gid) {
                    case 'NR':
                        $gid = 1;
                        break;
                    case 'NRTL':
                        $gid = 2;
                        break;
                    case 'PG':
                        $gid = 3;
                        break;
                    case 'PGTL':
                        $gid = 4;
                        break;
                    case 'BS':
                        $gid = 5;
                        break;
                    case 'BSTL':
                        $gid = 6;
                        break;
                    case 'MedNR':
                        $gid = 7;
                        break;
                }

                $newUser = array(
                'name' => $row['2'],
                'code' => trim($row['1']),
                'username' => trim($row['1']),                        
                'password' => md5($row['10']),

                'starting_day' => $row['3'],
                'stopping_day' => $row['4'] == ''? '':$row['4'],
                'title' => $row['5'],
                'location' => $row['6'],

                'teamleader_code' => trim($row['7']),
                'supervisor_code' => trim($row['8']),
                'rsm_code' => trim($row['9']),

                'identity_number' => $row['10'],
                'address' => $row['11'],
                'phone' => $row['12'],
                'email' => trim($row['13']),
                'status' => trim($row['14']),
                'note' => $row['15'],
                'gid' => $gid
                );

                if ($this->db->insert('users', $newUser) != false) {

                } else {
                    $fails[] = $row['0'];
                }
            }
        }
       
        if(count($fails) > 0)
        {
            return array('success' => false, 'data' => $fails);
        }
        else
        {
            return array('success' => true);
        }
    }
    
    // Tam
    function importUpdate($rows) {
        
        $fails = array();
        for($i = 1; $i<count($rows); $i++)
        {
            $row = $rows[$i];
            if ($row['1'] != '' ) {
                    
                $gid = 0;
                switch ($gid) {
                    case 'NR':
                        $gid = 1;
                        break;
                    case 'NRTL':
                        $gid = 2;
                        break;
                    case 'PG':
                        $gid = 3;
                        break;
                    case 'PGTL':
                        $gid = 4;
                        break;
                    case 'BS':
                        $gid = 5;
                        break;
                    case 'BSTL':
                        $gid = 6;
                        break;
                    case 'MedNR':
                        $gid = 7;
                        break;
                }
                
                $code = $row['1'];
                $newUser = array(
                'name' => $row['2'],
                //'code' => trim($row['1']),
                //'username' => trim($row['1']),                        
                'password' => md5($row['10']),

                'starting_day' => $row['3'],
                'stopping_day' => $row['4'] == ''? '':$row['4'],
                'title' => $row['5'],
                'location' => $row['6'],

                'teamleader_code' => trim($row['7']),
                'supervisor_code' => trim($row['8']),
                'rsm_code' => trim($row['9']),

                'identity_number' => $row['10'],
                'address' => $row['11'],
                'phone' => $row['12'],
                'email' => trim($row['13']),
                'status' => trim($row['14']),
                'note' => $row['15'],
                'gid' => $gid
                );

                if ($this->db->update('users', $newUser, "code like '$code'") != false) {

                } else {
                    $fails[] = $row['0'];
                }
            }
        }
       
        if(count($fails) > 0)
        {
            return array('success' => false, 'data' => $fails);
        }
        else
        {
            return array('success' => true);
        }
    }
    
    function replace($beReplaced, $replaceWith, $title)
    {
        $column = '';
        $set = array();
        switch ($title) {
            case 'RSM':
            case 'KAM':
                $column = 'rsm_code';
                $set['rsm_code'] = $replaceWith;
                break;
            case 'SS':
            case 'KAS':
                $column = 'supervisor_code';
                $set['supervisor_code'] = $replaceWith;
                break;
        }
        $result = $this->db->update('users', $set, "$column = '$beReplaced'"); // trả về true
        
        // nếu là thay thế ss thì thay thế rsm cho (cấp dưới của ss cũ, ss thay thế) luôn
//        if ($column == 'supervisor_code')
//        {
//            $result = $this->db->update('users', array('rsm_code' => 'a'), "rsm_code = '$beReplaced'");
//            var_dump($result);
//        }
        
        return $result;
    }
    
    function insert_user() {
        $institute_id = $this->session->userdata('institute_id');
        $insert_data = array(
            'username' => $this->input->post('username'),
            'password' => md5($this->input->post('user_password')),
            'first_name' => $this->input->post('first_name'),
            'last_name' => $this->input->post('last_name'),
            'credit' => $this->input->post('user_credit'),
            'email' => $this->input->post('user_email'),
            'gid' => $this->input->post('user_group'),
            'su' => $this->input->post('account_type'),
            'institute_id' => $institute_id
        );
        if ($this->db->insert('users', $insert_data)) {
            return "User added successfully";
        } else {
            return "Unable to add user";
        }
    }

    // get particular user detail		
    function get_user($user_id, $institute_id = "") {
        //$this->db->join("user_group", 'user_group.gid = users.gid');
        $query = $this->db->get_where('users', array('id' => $user_id));
        return $query->row_array();
    }

    function get_user_by_code($user_code) {
        //$this->db->join("user_group", 'user_group.gid = users.gid');

        $query = $this->db->get_where('users', array('code' => $user_code));        
        if ($query->num_rows() != 1) {
            return false;
        }
        return $query->row_array();
    }

    function get_user_by_email($email) {
        //$this->db->join("user_group", 'user_group.gid = users.gid');

        $query = $this->db->get_where('users', array('email' => $email));
        if ($query->num_rows() != 1) {
            return false;
        }
        return $query->row_array();
    }

    function get_user_by_username($username) {
        //$this->db->join("user_group", 'user_group.gid = users.gid');

        $query = $this->db->get_where('users', array('username' => $username));
        if ($query->num_rows() != 1) {
            return false;
        }
        return $query->row_array();
    }

    // update user detail
    function update_user($user_id) {
        $institute_id = $this->session->userdata('institute_id');
        $username = $_POST['username'];
        $name = $_POST['name'];
        $user_email = $_POST['user_email'];
        $user_password = $_POST['user_password'];
        $user_credit = $_POST['user_credit'];
        $user_group = $_POST['user_group'];
        $account_type = $_POST['account_type'];
        $logged_in = $this->session->userdata('logged_in');
        // if loged in user admin
        if ($logged_in['su'] == "1") {
            // if password changed
            if ($user_password != "") {
                $user_detail = array(
                    'username' => $username,
                    'name' => $name,
                    'email' => $user_email,
                    'credit' => $user_credit,
                    'gid' => $user_group,
                    'su' => $account_type,
                    'password' => md5($user_password)
                );
            } else {
                // if password not changed
                $user_detail = array(
                    'username' => $username,
                    'name' => $name,
                    'email' => $user_email,
                    'credit' => $user_credit,
                    'gid' => $user_group,
                    'su' => $account_type
                );
            }
        } else {
            // if loged in user not admin
            // if password changed
            if ($user_password != "") {
                $user_detail = array(
                    'name' => $name,
                    'password' => md5($user_password)
                );
            } else {
                // if password not changed
                $user_detail = array(
                    'name' => $name,
                );
            }
        }

        $this->db->where("institute_id", $institute_id);
        $this->db->where('id', $user_id);
        $this->db->update('users', $user_detail);
        return "User updated";
    }

    function update($userInfo) {
        $this->db->where('id', $userInfo['id']);
        $this->db->update('users', $userInfo);
        return "Đã cập nhật!";
    }

    //get all user limit
    function user_list_all($limit) {
        $institute_id = $this->session->userdata('institute_id');
        $this->db->select('*');
        $this->db->from('users');
        if ($this->input->post('search_type')) {
            $search_type = $this->input->post('search_type');
            $search = $this->input->post('search');
            $this->db->like($search_type, $search);
        }
        //$this->db->limit($this->config->item('number_of_rows'), $limit);
        $this->db->order_by("id", "ASC");
        $query = $this->db->get();
        if ($query->num_rows() >= 1) {
            return $query->result();
        } else {
            return false;
        }
    }

    function getCodeTitle() {
        $title = $_POST['select'];
        if ($title == "SS") {
            $where = "RSM";
        } else if ($title == "TL") {
            $where = "SS";
        } else {
            $where = "SS";
        }
        $this->db->select('name');
        $this->db->from('users');
        $this->db->where("rsm_code", $rsm_code);
        $query = $this->db->get();
        $result = $query->row();
        return $_POST['select'];
    }

    //get Name by Teamleader code
    function getNameTeamleader($teamleader_code) {
        //$institute_id = $this->session->userdata('institute_id');
        if ($teamleader_code) {
            $this->db->select('name');
            $this->db->from('users');
            $this->db->where("teamleader_code", $teamleader_code);
            $query = $this->db->get();
            $result = $query->row();
            return $result->name;
        } else {
            return "";
        }
    }

    //get Name by Supervisor code
    function getNameSupervisor($supervisor_code) {
        //$institute_id = $this->session->userdata('institute_id');
        if ($supervisor_code) {
            $this->db->select('name');
            $this->db->from('users');
            $this->db->where("supervisor_code", $supervisor_code);
            $query = $this->db->get();
            $result = $query->row();
            return $result->name;
        } else {
            return "";
        }
    }

    //get Name RSM by rsm code
    function getNameRSM($rsm_code) {
        //$institute_id = $this->session->userdata('institute_id');
        if ($rsm_code) {
            $this->db->select('name');
            $this->db->from('users');
            $this->db->where("rsm_code", $rsm_code);
            $query = $this->db->get();
            $result = $query->row();
            return $result->name;
        } else {
            return "";
        }
    }

    //get tiel in Database
    function get_enum_values() {
        $type = $this->db->query("SHOW COLUMNS FROM users WHERE Field = 'title'")->row(0)->Type;
        preg_match('/^enum\((.*)\)$/', $type, $matches);
        foreach (explode(',', $matches[1]) as $value) {
            $enum[] = trim($value, "'");
        }
        return $enum;
    }

}

?>
